﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TongTongMall.Oauth2._0.Owin.Middleware
{
    using Castle.Core.Logging;
    using global::Owin;
    using Logging;
    using Microsoft.Owin;
    using Newtonsoft.Json;
    using System.Net;
    using WebApi.Models;
    using AppFunc = Func<IDictionary<string, object>, Task>;
    public class GlobalExceptionHandlerMiddleware
    {
        private readonly AppFunc _next;

        public GlobalExceptionHandlerMiddleware(AppFunc next)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            _next = next;
        }

        public async Task Invoke(IDictionary<string, object> environment)
        {
            try
            {
                await _next(environment);
            }
            catch (Exception ex)
            {
                try
                {
                    var owinContext = new OwinContext(environment);
                    HandleException(ex, owinContext);
                    return;
                }
                catch (Exception)
                {
                }
                throw;
            }
        }
        private void HandleException(Exception ex, IOwinContext context)
        {
            var request = context.Request;
            LogHelper.LogException(ex);
            var errorDataModel = new AjaxResponse(ErrorInfoBuilder.Instance.BuildForException(ex.GetBaseException()), false);
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ReasonPhrase = "Internal Server Error";
            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(errorDataModel));
        }

    }


    public static class OwinExceptionHandlerMiddlewareAppBuilderExtensions
    {
        public static void UseOwinExceptionHandler(this IAppBuilder app)
        {
            app.Use<GlobalExceptionHandlerMiddleware>();
        }
    }
}
